package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.message.MessageConstant;
import com.itheima.pojo.OrderSetting;
import com.itheima.results.Result;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import com.itheima.utils.QiniuUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*预约设置*/
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    OrderSettingService orderSettingService;


    //文件上传到数据库 实现预约设置数据批量导入
    @RequestMapping("/upload.do")
    public Result upload( @RequestParam ("excelFile") MultipartFile excelFile){
        try {
            //使用poi解析表格数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            //解析后获得的数据是 封装为字符串数据格式的集合 为了方便我们操作我们将其封装为 OrderSetting 格式的集合
            List<OrderSetting> data = new ArrayList<>();
            //编辑集合 获得表格数据
            for (String[] strings : list) {
                String orderDate = strings[0];
                String number = strings[1];
                //将取出的数据 封装成OrderSetting 对象 再将该对象添加到泛型为OrderSetting的集合中
                OrderSetting orderSetting = new OrderSetting(new Date(orderDate), Integer.parseInt(number));
                data.add(orderSetting);
            }
            //通过dubbo 远程连接数据库
            orderSettingService.add(data);
        } catch (IOException e) {
            e.printStackTrace();
            //文件上传失败
            return  new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true , MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }
    //查询预约设置
    @RequestMapping("/getOrderSettingByMonth.do")
    public Result getOrderSettingByMonth(String date){
        try {
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            return  new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
    //单独设置可预约人数
    @RequestMapping("/editNumberByDate.do")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByDate(orderSetting);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
        return  new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
    }
}
